package com.cetccloud.ap.config;

import cn.hutool.core.net.NetUtil;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.eventbus.EventBusOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.spi.cluster.zookeeper.ZookeeperClusterManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class VertxConfig {

    @Value("${vertx.zookeeper.hosts:127.0.0.1}")
    private String zookeeperHosts;

    @Value("${vertx.eventbus.host}")
    private String eventbusHost;

    @Value("${vertx.eventbus.port:9000}")
    private int eventbusPort;

    @Bean
    public Vertx vertx() {
        return Vertx.vertx(new VertxOptions().setWorkerPoolSize(128));
    }

    private void buildClusteredVertx() {
        JsonObject zkConfig = new JsonObject();
        // default-zookeeper.json
        zkConfig.put("zookeeperHosts", zookeeperHosts);
        zkConfig.put("retry", new JsonObject().put("initialSleepTime", 3000).put("maxTimes", 3));

        if (StringUtils.isBlank(eventbusHost)) {
            // AddressHelper.defaultAddress()
            eventbusHost = NetUtil.getLocalhostStr();
        }
        if (!NetUtil.isUsableLocalPort(eventbusPort)) {
            eventbusPort = NetUtil.getUsableLocalPort(eventbusPort + 1);
            log.info("config eventbusPort is used, switch to: " + eventbusPort);
        }
        VertxOptions options = new VertxOptions().setWorkerPoolSize(128)
                .setClusterManager(new ZookeeperClusterManager(zkConfig))
                .setEventBusOptions(new EventBusOptions().setHost(eventbusHost).setPort(eventbusPort)
                );
        Vertx.clusteredVertx(options, res -> {
            if (res.succeeded()) {
                Vertx vertx = res.result();
                log.info("buildClusteredVertx success: {}", vertx);
            } else {
                log.error("buildClusteredVertx failed: ", res.cause());
            }
        });
    }
}
